﻿using System.Collections.Generic;
using System.Linq;
using System;

namespace VirtualRink.Library
{
	public class Roster
	{

		public static bool CanAddPlayer(IEnumerable<Player> players, Player newPlayer)
		{
			RosterCounts counts = RosterCounts.GetCounts(players);
			if (newPlayer.Position == "LW"
				&& counts.LeftWings == 0)
				return true;
			if (newPlayer.Position == "C"
							&& counts.Centers == 0)
				return true;
			if (newPlayer.Position == "RW"
				&& counts.RightWings == 0)
				return true;
			if (newPlayer.Position == "D"
				&& counts.Defense < 2)
				return true;
			if (newPlayer.Position == "G"
				&& counts.Goalies == 0)
				return true;

			throw new InvalidOperationException("Perhaps an unknown position was specified?");
		}

		public static bool CanReplacePlayer(IEnumerable<Player> players, Player oldPlayer, Player newPlayer)
		{
			RosterCounts counts = RosterCounts.GetCounts(players);

			if (oldPlayer.Position == "LW")
				counts.LeftWings--;
			else if (oldPlayer.Position == "C")
				counts.Centers--;
			else if (oldPlayer.Position == "RW")
				counts.RightWings--;
			else if (oldPlayer.Position == "D")
				counts.Defense--;
			else if (oldPlayer.Position == "G")
				counts.Goalies--;

			if (newPlayer.Position == "LW"
				&& counts.LeftWings == 0)
				return true;
			if (newPlayer.Position == "C"
				&& counts.Centers == 0)
				return true;
			if (newPlayer.Position == "RW"
				&& counts.RightWings == 0)
				return true;
			if (newPlayer.Position == "D"
				&& counts.Defense < 2)
				return true;
			if (newPlayer.Position == "G"
				&& counts.Goalies == 0)
				return true;

			return false;
		}

		public static bool IsValid(IEnumerable<Player> players)
		{
			if (players.Count() != 6)
				return false;

			RosterCounts counts = RosterCounts.GetCounts(players);

			if (counts.LeftWings != 1 || counts.RightWings != 1 ||
				counts.Centers != 1 || counts.Defense != 2 || counts.Goalies != 1)
				return false;

			return true;
		}
	}

	public class RosterCounts
	{
		public int LeftWings { get; set; }
		public int Centers { get; set; }
		public int RightWings { get; set; }
		public int Defense { get; set; }
		public int Goalies { get; set; }

		public static RosterCounts GetCounts(IEnumerable<Player> players)
		{
			RosterCounts counts = new RosterCounts();

			foreach (Player player in players)
			{
				switch (player.Position)
				{
					case "LW":
						counts.LeftWings++;
						break;
					case "RW":
						counts.RightWings++;
						break;
					case "C":
						counts.Centers++;
						break;
					case "D":
						counts.Defense++;
						break;
					case "G":
						counts.Goalies++;
						break;
				}
			}
			return counts;
		}

	}
}
